import { plugin, AMessage, getPluginHelp } from 'alemonjs'
import { command } from '../config/command'
import { AppName, DirPath } from '../app.config'
import fs from 'fs'
import axios from 'axios'

export class xianyu_tongji extends plugin {
  constructor() {
    super({
      dsc: '咸鱼插件统计',
      priority: 1,
      rule: [...command.tongji],
    })
  }

  async tongji(e: AMessage) {
    axios
      .get('https://www.schub.wiki/xyapi/userlist')
      .then((response) => {
        const obj = response.data
        if (obj.code == 200) {
          const list = {}
          obj.data.forEach((el: any) => {
            list[el.bot] = list[el.bot] ? list[el.bot] + 1 : 1
          })
          const botsname = Object.keys(list)
          let a = ''
          botsname.forEach((el: string) => {
            a += `\n${el}：${list[el]}人`
          })
          e.reply(`用户列表(机器人：数量)：${a}`)
        }
      })
      .catch((error) => {
        console.log(error)
        return false
      })
    return false
  }

  async adduser(e: AMessage) {
    let isok = false
    const command = getPluginHelp(AppName)
    // console.log('command', command)
    const botname = JSON.parse(fs.readFileSync(`./package.json`, 'utf-8'))
    command.forEach((el: any) => {
      if (el.doc != '咸鱼统计' && new RegExp(el.reg.replace(/^\//, '').replace(/\/[a-z]?$/, '')).test(e.msg)) {
        isok = true
        return
      }
    })
    if (!isok) return false

    const data = JSON.stringify({
      userid: e.user_id,
      nickname: e.user_name,
      plugin: AppName,
      bot: botname.name,
    })

    const config = {
      method: 'post',
      maxBodyLength: Infinity,
      url: 'https://www.schub.wiki/xyapi/adduser',
      headers: {
        'Content-Type': 'application/json',
      },
      data: data,
    }

    axios.request(config).catch((error) => {
      console.log(error)
      return false
    })
    return false
  }
}
